package com.fms.data.file;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import com.fms.model.domain.FlowSheet;
import com.fms.model.domain.IExistingFlowSheets;

public class XMLExistingFlowSheet implements IExistingFlowSheets
{
	private ExistingFlowSheetSet set;
	private String file;
	private List<FlowSheet> flowSheets;
	
	public XMLExistingFlowSheet(String _file)
	{
		this.file = _file;
		flowSheets = new ArrayList<FlowSheet>();
		load();
	}
	

	@Override
	public List<FlowSheet> getFlowSheets()
	{
		return flowSheets;
	}

	@Override
	public void registerNewFlowSheet(FlowSheet sheet)
	{
		ExistingFlowSheetSet.FlowSheetEntry entry = new ExistingFlowSheetSet.FlowSheetEntry();
		entry.setTargetDate(sheet.getDate());
		entry.setEmailed(false);
		entry.setEmailDate(null);
		entry.setFile(sheet.getFileName());
		
		set.getFlowSheetEntry().add(entry);
		flowSheets.add(sheet);
		save();
	}
	
	

	@Override
	public void registerAsEmailed(FlowSheet sheet)
	{
		for(ExistingFlowSheetSet.FlowSheetEntry entry : set.getFlowSheetEntry())
		{
			if(entry.getFile().equals(sheet.getFileName()))
			{
				entry.setEmailed(true);
				entry.setEmailDate(Calendar.getInstance());
			}
		}
		save();
		
	}


	@Override
	public Calendar getEmailedTime(int sheetIndex)
	{
		return set.getFlowSheetEntry().get(sheetIndex).getEmailDate();
	}


	@Override
	public boolean getWasEmailed(int sheetIndex)
	{
		return set.getFlowSheetEntry().get(sheetIndex).isEmailed();
	}
	
	private void load()
	{
		
		try
		{
			flowSheets.clear();
			JAXBContext c = JAXBContext.newInstance("com.fms.data.file");		
			set = (ExistingFlowSheetSet)c.createUnmarshaller().unmarshal(new File(file));
			for(ExistingFlowSheetSet.FlowSheetEntry entry : set.getFlowSheetEntry())
			{
				FlowSheet sheet = new FlowSheet(entry.getFile());
				sheet.setDate(entry.getTargetDate());
				
				flowSheets.add(sheet);
			}
		} 
		catch (JAXBException e)
		{
			set = new ExistingFlowSheetSet();
		}
	}
	
	private void save()
	{
		
		try
		{
			JAXBContext c = JAXBContext.newInstance("com.fms.data.file");
			Marshaller m = c.createMarshaller();
			m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));

			m.marshal(set, new File(file));
			
		} 
		catch (Exception e)
		{
			throw new RuntimeException("Unable to save flowsheet history to " + file);

		}
	}




}
